package com.sumainfor.pc.gmio.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumainfor.common.UnionPay.MapUtil;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.ObjectUtil;
import com.sumainfor.pc.gmio.dao.SurrenderMapper;
import com.sumainfor.pc.gmio.feign.BaseFeignZuul;
import com.sumainfor.pc.gmio.feign.BasePcMktFeign;
import com.sumainfor.pc.gmio.feign.BaseTenantFeign;
import com.sumainfor.pc.gmio.service.SurrenderService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-03-29 19:09
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SurrenderServiceImpl implements SurrenderService {

    @Autowired
    private SurrenderMapper surrenderMapper;


    @Autowired
    private BasePcMktFeign mktFeign;

    @Autowired
    private BaseFeignZuul feignZuul;

    @Autowired
    private BaseTenantFeign tenantFeign;


    /**
     * 获得表格数据
     *
     * @param params MiId: 服务中心编号
     *               City:城市名称
     *               District:区名称
     *               ComName:小区名称
     *               Date:时间 (格式 yyyy-MM-dd)
     * @param page
     * @return
     */
    @Override
    public JsonResult getTableList(Map<String, Object> params, Page page) {
        IPage<Map<String, Object>> result;
        String date = MapUtils.getString(params, "Date");
        if (StringUtils.isNotBlank(date)) {
            IPage<Map<String, Object>> surrender = surrenderMapper.selectSurrender(page, params);
            List<String> infoList = surrender.getRecords().stream().map(i1 -> MapUtils.getString(i1, "HouInfoId")).collect(Collectors.toList());
            if (infoList.isEmpty()) {
                return JsonResult.success(surrender);
            }
            params.put("infoIds", infoList);
            Page<Map<String, Object>> itemList = mktFeign.selectSurrenderList(CustomMap.create("size", Long.MAX_VALUE).put("current", 1), params);
            for (Map<String, Object> map : surrender.getRecords()) {
                for (int i = 0; i < itemList.getRecords().size(); i++) {
                    Map<String, Object> itemMap = itemList.getRecords().get(i);
                    if (map.get("HouInfoId").equals(itemMap.get("HouInfoId"))) {
                        map.putAll(itemMap);
                        itemList.getRecords().remove(i);
                        break;
                    }
                }
                if (initTableData(map)) {
                    return JsonResult.error("获取信息失败");
                }
            }
            result = surrender;
        } else {
            //时间不存在的时候
            IPage<Map<String, Object>> surrender = surrenderMapper.selectSurrender(new Page(1, Long.MAX_VALUE), CustomMap.create());
            List<String> infoList = surrender.getRecords().stream().map(i1 -> MapUtils.getString(i1, "HouInfoId")).collect(Collectors.toList());
            if (infoList.isEmpty()) {
                return JsonResult.success(page);
            }
            params.put("infoIds", infoList);
            Page<Map<String, Object>> itemList = mktFeign.selectSurrenderList(CustomMap.create("size", page.getSize()).put("current", page.getCurrent()), params);
            for (Map<String, Object> map : itemList.getRecords()) {
                Map<String, Object> infoMap = surrenderMapper.getSurrenderByHousingInfoId(MapUtils.getString(map, "HouInfoId"));
                map.putAll(infoMap);
                if (initTableData(map)) {
                    return JsonResult.error("获取信息失败");
                }
            }
            result = itemList;
        }
        return JsonResult.success(result);
    }

    /**
     * 初始化数据
     *
     * @param map
     * @return
     */
    private boolean initTableData(Map<String, Object> map) {
        //获得管家名称
        String launchId = MapUtils.getString(map, "LaunchId");
        String auditId = MapUtils.getString(map, "AuditId");
        map.put("LaunchName", "-");
        map.put("AuditName", "-");
        JsonResult<List<Map<String, Object>>> userInfo = feignZuul.getUserInfo(Arrays.asList(launchId, auditId));
        if (!userInfo.isSuccess() || CollectionUtils.isEmpty(userInfo.getResult())) {
            return true;
        }

        for (Map<String, Object> uInfo : userInfo.getResult()) {
            if (MapUtils.getString(uInfo, "user_id").equals(launchId)) {
                map.put("LaunchName", uInfo.get("username"));
            } else {
                map.put("AuditName", uInfo.get("username"));
            }
        }

        //获取租客信息
        JsonResult tenInfo = tenantFeign.getWxInfoByTenId(MapUtils.getString(map, "TenId"));
        if (!tenInfo.isSuccess()) {
            log.info("Error ==> {}", tenInfo.getErrorMessage());
            throw new TCException("没有查询到租客的信息");
        }
        WxUserEntity entity = JSONObject.parseObject(((JSONObject) tenInfo.getResult()).toJSONString(), WxUserEntity.class);
        //租客姓名
        map.put("TenUserName", entity.getRealName());
        map.put("TenPhone", entity.getTenPhone());
        return false;
    }


    /**
     * 获取详细信息数据
     *
     * @param witId 主表编号
     * @return
     */
    @Override
    public JsonResult getInfo(String witId) {
        Map<String, Object> info = surrenderMapper.getSurrenderById(witId);
        if (MapUtils.isEmpty(info)) {
            return JsonResult.error("不存在的数据");
        }
        //查合同到期时间
        String pastTime = mktFeign.getPactPastTime(MapUtils.getString(info, "PaId"));
        info.put("PastTime", pastTime);
        //查询活动名称
        String actId = MapUtils.getString(info, "ActId");
        info.put("ActivateName", "-");
        if (StringUtils.isNotBlank(actId)) {
            String actName = mktFeign.getActivateNameById(actId);
            info.put("ActivateName", actName);
        }
        return JsonResult.success(info);
    }

}
